import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { db, prisma } from '@/lib/db';

// 获取用户资料信息
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    // 获取用户ID，添加await修复参数问题
    const userId = await params.id;
    
    // 验证userId格式
    if (!userId || typeof userId !== 'string') {
      return NextResponse.json(
        { error: '无效的用户ID' },
        { status: 400 }
      );
    }
    
    // 获取用户基本信息
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        name: true,
        email: true,
        image: true,
        createdAt: true,
      }
    });
    
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 获取用户资料
    const profile = await prisma.userProfile.findUnique({
      where: { userId },
      select: {
        bio: true,
        jobTitle: true,
        location: true,
        skills: true,
        socialLinks: true,
      }
    });

    // 组合返回数据
    const responseData = {
      ...user,
      ...(profile || {}),
      joinedAt: user.createdAt,
      bio: profile?.bio || '',
      jobTitle: profile?.jobTitle || '',
      location: profile?.location || '',
      skills: profile?.skills || [],
      socialLinks: profile?.socialLinks || {},
    };

    return NextResponse.json(responseData);
  } catch (error) {
    console.error('获取用户资料失败:', error);
    return NextResponse.json(
      { error: '获取用户资料失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

// 更新用户资料 - PATCH方法
export async function PATCH(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    // 获取会话验证身份
    const session = await auth();
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }
    
    // 修复：使用 await 获取 params.id
    const userId = await params.id;
    
    // 验证是否为本人操作
    const currentUser = await prisma.user.findUnique({
      where: { email: session.user.email }
    });
    
    if (!currentUser || (currentUser.id !== userId)) {
      return NextResponse.json(
        { error: '无权更新此用户资料' },
        { status: 403 }
      );
    }
    
    // 解析请求数据
    const data = await req.json();
    
    // 验证数据
    const validUserFields = ['name'];
    const validProfileFields = ['bio', 'jobTitle', 'location', 'skills', 'socialLinks'];
    
    // 分离用户表和用户资料表的字段
    const userUpdateData = Object.keys(data)
      .filter(key => validUserFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);
    
    const profileUpdateData = Object.keys(data)
      .filter(key => validProfileFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);

    // 开始事务，同时更新用户和用户资料
    const [updatedUser, updatedProfile] = await prisma.$transaction([
      // 更新用户基本信息
      prisma.user.update({
        where: { id: userId },
        data: userUpdateData,
        select: {
          id: true,
          name: true,
          email: true,
          image: true,
          createdAt: true,
        }
      }),
      
      // 更新或创建用户资料
      prisma.userProfile.upsert({
        where: { userId },
        update: profileUpdateData,
        create: {
          userId,
          ...profileUpdateData,
        },
        select: {
          bio: true,
          jobTitle: true,
          location: true,
          skills: true,
          socialLinks: true,
        }
      })
    ]);

    // 组合返回数据
    const responseData = {
      ...updatedUser,
      ...updatedProfile,
      joinedAt: updatedUser.createdAt,
    };

    return NextResponse.json(responseData);
  } catch (error) {
    console.error('更新用户资料失败:', error);
    return NextResponse.json(
      { error: '更新用户资料失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
}

// 更新用户资料 - PUT方法
export async function PUT(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    // 获取会话验证身份
    const session = await auth();
    
    if (!session?.user?.email) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }
    
    // 修复：使用 await 获取 params.id
    const userId = await params.id;
    
    // 验证是否为本人操作
    const currentUser = await prisma.user.findUnique({
      where: { email: session.user.email }
    });
    
    if (!currentUser || (currentUser.id !== userId)) {
      return NextResponse.json(
        { error: '无权更新此用户资料' },
        { status: 403 }
      );
    }
    
    // 解析请求数据
    const data = await req.json();
    
    // 验证数据
    const validUserFields = ['name'];
    const validProfileFields = ['bio', 'jobTitle', 'location', 'skills', 'socialLinks'];
    
    // 分离用户表和用户资料表的字段
    const userUpdateData = Object.keys(data)
      .filter(key => validUserFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);
    
    const profileUpdateData = Object.keys(data)
      .filter(key => validProfileFields.includes(key))
      .reduce((obj, key) => {
        obj[key] = data[key];
        return obj;
      }, {} as Record<string, any>);

    // 开始事务，同时更新用户和用户资料
    const [updatedUser, updatedProfile] = await prisma.$transaction([
      // 更新用户基本信息
      prisma.user.update({
        where: { id: userId },
        data: userUpdateData,
        select: {
          id: true,
          name: true,
          email: true,
          image: true,
          createdAt: true,
        }
      }),
      
      // 更新或创建用户资料
      prisma.userProfile.upsert({
        where: { userId },
        update: profileUpdateData,
        create: {
          userId,
          ...profileUpdateData,
        },
        select: {
          bio: true,
          jobTitle: true,
          location: true,
          skills: true,
          socialLinks: true,
        }
      })
    ]);

    // 组合返回数据
    const responseData = {
      ...updatedUser,
      ...updatedProfile,
      joinedAt: updatedUser.createdAt,
    };

    return NextResponse.json(responseData);
  } catch (error) {
    console.error('更新用户资料失败:', error);
    return NextResponse.json(
      { error: '更新用户资料失败', details: error instanceof Error ? error.message : String(error) },
      { status: 500 }
    );
  }
} 